#!/usr/bin/python

import zutil
import zbuild_parser
import zbuild_scanner
import zbuild_token

from optparse import OptionParser
import sys

def get_v8_dir():

    parser = OptionParser()
    parser.add_option("-d", "--dir", help="set the target v8 dir in which zed will be installed", default="..")
    (options, args) = parser.parse_args()

    the_dir = options.dir
    #print the_dir
    return the_dir


def build():
    """ The following files will be updated to allow V8 to
    execute both zedscript and javascript files.
    
    Updated files:
    - parser.cc
    - scanner.h and scanner.cc
    - token.h and token.cc
    
    Note: the updated parser.cc #include's the zparser.cc file
    which contains the bulk of the zedscript functionality.
    """
 
    print("*** Start ***")
    
    the_v8_dir = get_v8_dir()

    # Fix the v8 dir to update by uncommenting and setting this var
    #the_v8_dir = "../v8test"
    
    # double check that the v8_dir has been set
    if the_v8_dir == None or the_v8_dir.strip() == "":
        sys.exit("Error: the_v8_dir var has not been set")
    
    # set the v8 dir. If dir not found the script will terminate.
    zutil.set_v8_dir(the_v8_dir)
    
    # copy files to bak dir.
    # Note: the build_xxx.py scripts which follow all read 
    # files from the bak dir. This means this script can 
    # be run repeatedly
    # Note: the updated files are written back to the src dir

    zutil.backup_files()
    
    # Generate the updated files
    print "--- Updating files in src dir: %s " %(','.join(zutil._files))
    zbuild_parser.main()
    zbuild_scanner.main()
    zbuild_token.main()
    
    # Copy the zparser file
    zutil.copy_zparser_file()
    
    # Copy the dir of zed tests
    zutil.copy_test_dir()
    
    print("*** End ***")
    
# main function
build()
